<template>
  <ex-dialog width="900px" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="labelWidth" class="demo-ruleForm">
        <el-form-item label="店铺行业：" prop="industryId" :key="1">
          <el-select v-model="ruleForm.industryId" placeholder="请选择店铺行业" filterable :style="{width: inputWidth}">
            <el-option v-for="item in shopList" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺类型：" prop="type" :key="2">
          <el-select v-model="ruleForm.type" placeholder="请选择店铺类型" filterable :disabled="disabled"
            :style="{width: inputWidth}" @change="typeChange">
            <el-option v-for="item in shopTypeList" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺名称：" prop="name" ref="refOne" :key="3">
          <el-input v-model="ruleForm.name" placeholder="请输入店铺名称" :style="{width: inputWidth}" maxlength="50">
          </el-input>
        </el-form-item>
        <el-form-item label="店铺简称：" prop="shortName" ref="refOne" :key="4">
          <el-input v-model="ruleForm.shortName" placeholder="请输入店铺简称" :style="{width: inputWidth}" maxlength="10">
          </el-input>
        </el-form-item>
        <el-form-item label="店铺定位：" prop="address" ref="addressRef" v-if="ruleForm.type!=2" :key="5">
          <span class="fontsize">{{ ruleForm.address }}</span>
          <!-- <el-input v-model="ruleForm.address" :disabled="true" v-show="false"></el-input> -->
          <span class="fontsize" @click="modelMsg = true"
            style="color: #1890ff; margin-left: 30px; cursor: pointer">选择定位</span>
        </el-form-item>
        <el-form-item label="营业时间：" prop="shortName" ref="refOne" :key="4">
          <el-input v-model="ruleForm.businessTime" placeholder="请输入营业时间" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="营业时间：" required :label-width="labelWidth" v-if="ruleForm.type!=2" :key="6">
          <el-col :span="8">
            <el-form-item prop="startTime">
              <el-time-select v-model="ruleForm.startTime" placeholder="开始时间" :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00',
                  }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1" style="margin-left:10px">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-select v-model="ruleForm.endTime" placeholder="结束时间" :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00',
                  }">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-form-item> -->
        <el-form-item label="登录账号：" prop="account" v-if="ruleForm.type!=2" :key="7">
          <el-input v-model="ruleForm.account" placeholder="请输入登录账号" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <el-form-item label="登录密码：" prop="password" v-if="ruleForm.type!=2&&passwordIsShow" :key="8">
          <el-input v-model="ruleForm.password" placeholder="请输入登录密码" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <el-form-item label="登录密码：" prop="" v-if="ruleForm.type!=2&&!passwordIsShow" :key="9">
          <el-input v-model="ruleForm.password" placeholder="请输入登录密码" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="phone" v-if="ruleForm.type!=2" :key="10">
          <el-input v-model="ruleForm.phone" placeholder="请输入联系电话" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sort" :key="11">
          <el-input v-model.number="ruleForm.sort" placeholder="请输入排序" :style="{width: inputWidth}">
          </el-input>
        </el-form-item>
        <el-form-item label="店铺logo：" prop="" ref="imgRef">
          <ImageUploadMore :limit="1" :fileSize="20" @successImg="getLogoImg" :value="ruleForm.logo">
          </ImageUploadMore>
        </el-form-item>
        <el-form-item label="店铺图片：" prop="" ref="shopImgRef" v-if="ruleForm.type!=2">
          <ImageUploadMore :limit="6" :fileSize="20" @successImg="getShopImg" :value="ruleForm.shopImgList">
          </ImageUploadMore>
        </el-form-item>
        <el-form-item label="店铺资质：" prop="" ref="shopCertificationImgRef" v-if="ruleForm.type!=2">
          <ImageUploadMore :limit="6" :fileSize="20" @successImg="getShopCertificationImg"
            :value="ruleForm.shopCertificationImgList">
          </ImageUploadMore>
        </el-form-item>
        <el-form-item label="是否启用：" prop="status" required>
          <el-switch v-model="ruleForm.status" :active-value="'1'" :inactive-value="'2'" active-text="启用"
            inactive-text="停用">
          </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <div class="button_box">
      <el-button type="primary" :loading="AgreeLoading" @click="submitForm('ruleForm')" v-if="id==null">立即创建</el-button>
      <el-button type="primary" :loading="AgreeLoading" @click="editForm('ruleForm')" v-if="id!=null">保存提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
    <el-dialog title="选择定位" :visible.sync="modelMsg" append-to-body :close-on-click-modal="false">
      <div class="msgDiv">
        <el-autocomplete style="width: 80%; margin-right: 10px" class="inline-input" v-model="address"
          :fetch-suggestions="watchInput" placeholder="请输入内容" :trigger-on-focus="false" @select="handleSelect">
        </el-autocomplete>
        <div id="container" style="margin-top: 20px"></div>
        <div class="dialog_bottom">
          <el-button style="margin-right: 60px" @click="modelMsg = false">取消</el-button>
          <el-button type="primary" @click="determine">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </ex-dialog>
</template>
<script>
  import Loading from "@/components/Loading/index";
  // api
  import {
    addShenyeShop,
    shenyeShopDetail,
    updateShenyeShop,
    shopIndustrySelect,
  } from "@/api/consumeMiningManagement/clockShopConfiguration";

  export default {
    components: {
      Loading,
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      return {
        labelWidth: '120px',
        inputWidth: '300px',
        modelMsg: false, //显示模态框
        address: "", //输入的地址
        mapList: [], //用来存搜索到的所有地址
        mapVal: "", //创建的地图，赋值用
        title: '新增',
        loading: false,
        disabled: false,
        info: {},
        passwordIsShow: true, //密码是否必填
        AgreeLoading: false, //按钮loading
        shopTypeList: [], //店铺类型字典数组
        dateTime: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
        shopList: [], //店铺行业数组
        ruleForm: {
          id: '', //id,编辑时才传
          type: '', //店铺类型 shenye_shop_type
          logo: '', //店铺logo
          name: '', //店铺名称
          shortName: '', //店铺简称
          lnt: '', //店铺经度
          lat: '', //店铺纬度
          address: '', //店铺地址
          startTime: '', //营业开始时间
          endTime: '', //营业结束时间
          account: '', //登录帐号
          password: '', //登录密码
          status: '', //状态 shenye_shop_status
          sort: '', //排序号
          shopImgList: [], //店铺图片数组
          shopCertificationImgList: [], //店铺资质图片数组
          phone: '', //联系电话
          industryId: '', //店铺行业
          businessTime:'',//营业时间
        },
        rules: {
          type: [{
            required: true,
            message: '请选择店铺类型',
            trigger: 'change'
          }],
          name: [{
            required: true,
            message: "请输入店铺名称",
            trigger: ['change', 'bulr'],
          }],
          shortName: [{
            required: true,
            message: "请输入店铺简称",
            trigger: ['change', 'bulr'],
          }],
          address: [{
            required: true,
            message: "请选择店铺定位",
            trigger: ['change', 'bulr'],
          }],
          startTime: [{
            required: true,
            message: '请选择营业开始时间',
            trigger: 'change'
          }],
          endTime: [{
            required: true,
            message: '请选择营业结束时间',
            trigger: 'change'
          }],
          account: [{
            required: true,
            message: "请输入登录账号",
            trigger: ['change', 'bulr'],
          }],
          password: [{
            required: true,
            message: "请输入登录密码",
            trigger: ['change', 'bulr'],
          }],
          sort: [{
            required: true,
            type: 'number',
            message: "请输入正确排序号",
            trigger: ['change', 'bulr'],
          }],
          industryId: [{
            required: true,
            message: '请选择店铺行业',
            trigger: 'change'
          }],
          phone: [{
            required: true,
            message: "请输入联系电话",
            trigger: ['change', 'bulr'],
          }],
          businessTime: [{
            required: true,
            message: "请输入营业时间",
            trigger: ['change', 'bulr'],
          }],
        },
      };
    },
    computed: {},
    watch: {
      //监听模态框是否显示,显示就执行初始化地图方法
      modelMsg(newVal, oldVal) {
        console.log(newVal);
        if (newVal == true) {
          this.initMap(20.049818248, 110.354108124);
        }
      },
    },
    created() {
      this.getDict();
      this.getShopIndustrySelect();
      console.log(this.id)
      if (this.id != null) {
        this.title = '编辑'
        this.disabled = true
        this.passwordIsShow = false
        this.getInfo()
      }

    },
    mounted() {

    },
    methods: {
      //获取店铺类型字典
      getDict() {
        var dictType = "shenye_shop_type";
        this.$getSelectList(dictType)
          .then((res) => {
            this.shopTypeList = res.result[0].dictList;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      getShopIndustrySelect() { //查询行业下拉框
        this.loading = true
        shopIndustrySelect(this.id).then((res) => {
            this.shopList = res.result
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 获取logo
      getLogoImg(e) {
        this.ruleForm.logo = e
        this.$refs['imgRef'].clearValidate();
      },
      getShopImg(e) { //获取店铺图片
        console.log('e', e)
        if (e != '') {
          this.ruleForm.shopImgList = e.split(",")
        } else {
          this.ruleForm.shopImgList = []
        }
      },
      getShopCertificationImg(e) { //获取店铺资质图片图片
        console.log('e', e)
        if (e != '') {
          this.ruleForm.shopCertificationImgList = e.split(",")
        } else {
          this.ruleForm.shopCertificationImgList = []
        }
      },
      //商品类型选择
      typeChange(e) {
        // this.$refs['addressRef'].clearValidate();
      },
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      handleSelect(item) { //地图搜索
        console.log(item);
        this.initMap(item.location.lat, item.location.lng);
        this.ruleForm.lnt = item.location.lng;
        this.ruleForm.lat = item.location.lat;
        console.log(this.ruleForm.lnt, this.ruleForm.lat)
      },
      determine() { ////地图搜索确定
        console.log(this.address);
        this.ruleForm.address = this.address;
        this.modelMsg = false;
        this.$refs['addressRef'].clearValidate();
        console.log(this.ruleForm.lnt, this.ruleForm.lat)
      },
      watchInput(queryString, cb) {
        console.log(queryString);
        const KEY = "IFRBZ-GZ2CQ-YHW5J-GSUGE-RC7VS-JBBWN";
        let url = "https://apis.map.qq.com/ws/place/v1/suggestion";
        let keyword = queryString; //传入的关键词
        this.$jsonp(url, {
            key: KEY,
            region: "全国",
            keyword: keyword,
            output: "jsonp",
          })
          .then((res) => {
            let opt = [];
            res.data.forEach((res) => {
              let opt1 = {
                value: res.title + "-" + res.address,
                location: res.location,
              };
              opt.push(opt1);
            });
            this.mapList = opt;
            console.log(this.mapList);
            // 调用 callback 返回建议列表的数据
            cb(this.mapList);
          })
          .catch((err) => {
            console.log(err);
          });
      },
      initMap(lat, lng) {
        //如果地图存在，就销毁，下面会重新创建一个
        if (this.mapVal) {
          this.mapVal.destroy();
        }
        //定义地图中心点坐标
        //this.$nextTick是等Dom加载完再执行
        this.$nextTick(() => {
          var center = new window.TMap.LatLng(lat, lng);
          //定义map变量，调用 TMap.Map() 构造函数创建地图
          this.mapVal = new TMap.Map(document.getElementById("container"), {
            center: center, //设置地图中心点坐标
            zoom: 17.2, //设置地图缩放级别
            pitch: 43.5, //设置俯仰角
            rotation: 45, //设置地图旋转角度
            viewMode: "2D",
            mapStyleId: "style1", //个性化样式
          });
          //初始化marker
          var marker = new TMap.MultiMarker({
            id: "marker-layer", //图层id
            map: this.mapVal,
            styles: {
              //点标注的相关样式
              marker: new TMap.MarkerStyle({
                width: 25,
                height: 35,
                anchor: {
                  x: 16,
                  y: 32,
                },
                src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
              }),
            },
            geometries: [{
              //点标注数据数组
              id: "demo",
              styleId: "marker",
              position: new TMap.LatLng(lat, lng),
              properties: {
                title: "marker",
              },
            }, ],
          });
        });
      },
      getInfo() { //获取信息详情
        this.loading = true
        shenyeShopDetail(this.id).then((res) => {
            this.loading = false
            this.ruleForm = res.result
          })
          .finally(() => {
            this.loading = false;
          });
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // if (this.ruleForm.content == '') {
            //   this.$message.error('请填写文章内容');
            //   return
            // }
            this.AgreeLoading = true
            var params = {
              ...this.ruleForm,
            };
            addShenyeShop(params).then((res) => {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  // setTimeout(() => {
                  //   this.AgreeLoading = false
                  // }, 2000)
                  this.AgreeLoading = false
                }, 1000);
              })
              .catch(() => {
                this.AgreeLoading = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            this.AgreeLoading = true
            var params = {
              id: this.id,
              ...this.ruleForm,
            };
            updateShenyeShop(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeLoading = false
                }, 1000);
              })
              .catch(() => {
                this.AgreeLoading = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  .main {
    padding: 20px 20px;
  }

  .from_box {
    display: flex;
    margin-bottom: 20px;
  }

  .from_box_l {
    width: 110px;
    color: #606266;
    font-size: 14px;
    font-weight: bold;
  }

  .from_box_r {
    color: #333;
    font-size: 15px;
    flex: 1;
  }

  .el_table_box {
    padding: 0 20px 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .el_table_box_h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f3f3;
    margin-bottom: 14px;
  }

  .el_table_box_h_title {
    border-left: 4px solid #ff9300;
    padding-left: 4px;
  }

  .carousel_box {
    width: 400px;
    margin-bottom: 20px;
  }

  .swiper_img {
    width: 100%;
    height: 100%;
  }

  .carousel_box_two {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .phone_box {
    width: 100px;
    height: 100px;
    margin: 0 10px 10px 0;
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 228px;
    height: 128px;
    text-align: center;
    line-height: 128px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 228px;
    height: 128px;
  }

  .richText {
    border: 1px solid #ccc;
    line-height: normal;
  }

</style>
